package com.zx.znav.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zx.znav.bean.LinkTag;
import com.zx.znav.bean.Tag;
import com.zx.znav.constant.Constants;
import com.zx.znav.error.BusinessException;
import com.zx.znav.error.EnumBusinessError;
import com.zx.znav.response.CommonReturnType;
import com.zx.znav.service.LinkTagService;
import com.zx.znav.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 挚爱之夕
 * @version 1.0
 * @implSpec 后台标签管理
 * @since 2023-07-20 18:28
 */
@Controller
@RequestMapping("/admin/tag")
public class TagController {
    @Autowired
    private TagService tagService;
    @Autowired
    private LinkTagService linkTagService;

    @RequestMapping
    public String index(Model model){
        //查标签数据
        model.addAttribute(Constants.TAG_KEY, tagService.listTags());
        return "admin/tag";
    }
    //新增
    @PostMapping("/add")
    @ResponseBody
    public Object add(Tag tag) throws BusinessException {
        try {
            boolean save = tagService.save(tag);
            if (!save) {  //添加失败
                throw new BusinessException(EnumBusinessError.OPERATOR_ERROR);
            }
        } catch (Exception e) { //SQL异常
            throw new BusinessException(EnumBusinessError.NAME_EXISTS);
        }
        return CommonReturnType.create(tag);
    }
    //修改
    @PutMapping("/update")
    @ResponseBody
    public Object update(Tag tag) throws BusinessException {
        try {
            tagService.updateById(tag);
        } catch (Exception e) { //SQL异常
            throw new BusinessException(EnumBusinessError.NAME_EXISTS);
        }
        return CommonReturnType.create(tag);
    }
    //根据id查找
    @GetMapping("/get")
    @ResponseBody
    public Object get(Integer id){
        return CommonReturnType.create(tagService.getById(id));
    }
    //查找所有
    @ResponseBody
    @GetMapping("/list")
    public Object list(){
        return  CommonReturnType.create(tagService.listTags());
    }
    //删除
    @DeleteMapping("/delete/{id}")
    @ResponseBody
    public Object delete(@PathVariable Integer id) throws BusinessException {
        //标签下有链接不可删除
        LambdaQueryWrapper<LinkTag> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LinkTag::getTagId, id);
        int count = linkTagService.count(wrapper);
        if(count > 0){
            throw new BusinessException(EnumBusinessError.TAG_LINK_EXISTS);
        }
        //删除
        tagService.removeById(id);
        return CommonReturnType.create("删除成功!");
    }

    //搜索
    @GetMapping("/search")
    @ResponseBody
    public Object search(String name){
        List<Tag> tagList = tagService.search(name);
        return CommonReturnType.create(tagList);
    }
}
